package tg.edu.fhh.demo.web.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tg.edu.fhh.demo.custom.AjaxResult;
import tg.edu.fhh.demo.custom.FileUtils;
import tg.edu.fhh.demo.entity.TbFile;
import tg.edu.fhh.demo.service.TbFileService;
import tg.edu.fhh.demo.web.form.TbFileForm;

@Controller
@RequestMapping(value = "/file")
public class FileController {
	@Autowired
	private TbFileService fileservice;
	
	@Value("${web.file-path}")
	private String path;
	
	@Autowired
	private FileUtils fileUtils;
	
	@RequestMapping(value = "/manage")
	public void manage() {
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Object list() {
		return fileservice.findAll();
	}
	
	@RequestMapping(value = "/edit")
	public void edit(Integer id,ModelMap modelMap) {
		TbFile model=new TbFile();
		if(id!=null) {
			model=fileservice.findById(id);
		}
		modelMap.put("model", model);
	}
	
	@RequestMapping(value = "/save")
	public String save(TbFileForm form) {
		fileservice.upload(form);
		return "redirect:manage";
	}
	
	@RequestMapping(value = "/download")
	@ResponseBody
	public Object download(Integer id,HttpServletRequest request,HttpServletResponse response) {
		TbFile tbFile = fileservice.findById(id);
		String uuid = tbFile.getUuid();
		String filename = tbFile.getFilename();
		fileUtils.download(request, response, uuid, filename);
		return null;
	}
	
	@RequestMapping(value = "/preview")
	public void preview() {
		
	}
	
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(Integer id) {
		boolean flag=fileservice.delete(id);
		HashMap<String, Object> result=new HashMap<>();
		if(flag) {
			result.put("success", true);
			result.put("msg", "删除成功");
		}else {
			result.put("success", false);
			result.put("msg", "删除失败");
			
		}
		return result;
	}
	
	@RequestMapping(value = "/edit2")
	public void edit2(Integer id,ModelMap modelMap) {
		TbFile model=new TbFile();
		if(id!=null) {
			model=fileservice.findById(id);
		}
		modelMap.put("model", model);
	}
	
	@RequestMapping(value = "/save2")
	@ResponseBody
	public Object save2(TbFileForm form) {
		fileservice.upload(form);
		return new AjaxResult("保存成功");
	}
}
